<template>
  <view class="sign_page">
    <view class="sign-container">
      <canvas
        canvas-id="canvas"
        @touchstart="touchstart"
        @touchmove="touchmove"
		style="width: 100%;height: 100%; display: block;"
      >
      </canvas>
    </view>
    <div class="sign-button-group">
      <van-button @click="saveSign" type="info">
        上传签名
      </van-button>
      <van-button @click="clear" type="danger">
        清除签名
      </van-button>
    </div>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        hasDraw: false,
        context1: null,
		callback: ''
      };
    },
    onLoad (e) {
		this.callback = e.callback
		console.log(this.callback)
      var context1 = uni.createCanvasContext('canvas')
      context1.setStrokeStyle("#000000")
      context1.setLineWidth(3)
      this.context1 = context1
    },
    methods: {
      touchstart (e) {
        var context1 = this.context1
        context1.moveTo(e.touches[0].x, e.touches[0].y)
        this.context1 = context1
        this.hasDraw = true
      },
      touchmove (e) {
        var x = e.touches[0].x
        var y = e.touches[0].y
        var context1 = this.context1
        context1.setLineWidth(3)
        context1.lineTo(x, y)
        context1.stroke()
        context1.setLineCap('round')
        context1.draw(true)
        context1.moveTo(x, y)
	  },
	  clear () {
		  this.context1.draw()
		  this.hasDraw = false
		  this.src = null
	  },
	  saveSign () {
		  if(!this.hasDraw){
			uni.showToast({
				title: '请完成签名后再保存提交',
				icon: 'none'
			})
		  }else{
			  const _self = this
			var context1 = this.context1;
			context1.draw(true, uni.canvasToTempFilePath({
			  canvasId: 'canvas',
			  success: (res) => {
				this.src = res.tempFilePath
				// 这里开始返回到上一页，并且携带参数回去
				// { tempPath, callBackType }
				uni.$emit('handleSaveSign', { tempPath: res.tempFilePath, callBackType: this.callback })
				uni.navigateBack({
					delta:1
				})
				// wx.uploadFile({
				//   url: "http://**************",
				//   filePath: res.tempFilePath,
				//   name: "file",
				//   formData: {
				//     filetype: "image",
				//   },
				//   success: function (result) {
				//     console.log(result)
				//   }
				// })
			  }
			}))
		  }
	  }
    }
  }
</script>

<style lang="scss">
.sign_page{
  display: flex;
  flex-direction: column;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  .sign-container{
    flex: 1;
    height: 0;
    border: 1px solid #000000;
    canvas {
      height: 100%;
      width: 100%;
      display: block !important;
    }
  }
  .sign-button-group {
    padding: 32rpx;
    box-sizing: border-box;
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
}
</style>
